#include <termios.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdint.h>
#include "public.h"

extern int handle_msg_from_serial(node_t data);

#define DEV_UART "/dev/ttyUSB0"

static int fd;  //串口文件描述符

static void set_opt()
{
    struct termios options;
    tcgetattr(fd, &options);
    options.c_cflag |= ( CLOCAL | CREAD );
    options.c_cflag &= ~CSIZE;
    options.c_cflag &= ~CRTSCTS;
    options.c_cflag |= CS8;
    options.c_cflag &= ~CSTOPB;
    options.c_iflag |= IGNPAR;
    options.c_iflag &= ~(ICRNL | IXON);
    options.c_oflag = 0;
    options.c_lflag = 0;

    cfsetispeed(&options, B115200);
    cfsetospeed(&options, B115200);
    tcsetattr(fd,TCSANOW,&options);
}

void *pthread_serial(void *arg)
{
    node_t data;
    int nbytes = 0;

    while (1)
    {
        nbytes = read(fd, &data, SIZE_NODE);
        if(nbytes != SIZE_NODE)
        {
            continue;
        }

        //从串口来的数据，应该上报给QT客户端
        handle_msg_from_serial(data);
    }
}

int serial_write(node_t data)
{
    return write(fd, &data, SIZE_NODE);
}

int serial_init()
{
    pthread_t pid;
    fd = open(DEV_UART, O_RDWR);
    if (fd < 0)
    {
        perror ("open uart err\n");
        return -1;
    }

    set_opt();

    return pthread_create(&pid, NULL, pthread_serial, NULL);
}
